import { Component, forwardRef, Input, Injector } from '@angular/core'
import { NG_VALUE_ACCESSOR } from '@angular/forms'
import { Observable } from 'rxjs'
import { RiskControlScheme, IRiskControlSchemeQuery } from '@shared/interfaces/risk-control'
import { RiskControlService } from './risk-control.service'
import { AbstractCustomSelectComponent } from '../custom-select/custom-select.component'
import { IGenericPagination } from '@shared/interfaces/pagination'
import { objectArrayDeduplication } from '../../../utils/helpers'
@Component({
  selector: 'app-risk-control-select',
  templateUrl: './risk-control-select.component.html',
  styles: [],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => RiskControlSelectComponent),
      multi: true,
    },
  ],
})
export class RiskControlSelectComponent extends AbstractCustomSelectComponent<
  RiskControlScheme,
  IRiskControlSchemeQuery
> {
  constructor(private riskControlService: RiskControlService, public injector: Injector) {
    super(injector)
  }

  @Input() insCode = ''
  _params: IRiskControlSchemeQuery = {
    limit: 10,
    size: 10,
    page: 1,
    keyword: '',
  }

  /**
   * 是否查询事后风控方案列表
   */
  @Input() isPostpositive = false

  @Input() placeholder: string
  deduplicate(list: RiskControlScheme[]): RiskControlScheme[] {
    return objectArrayDeduplication(list, 'schemeCode')
  }

  compareFn = (o1: RiskControlScheme, o2: RiskControlScheme) => {
    return o1 && o2 ? o1.schemeCode === o2.schemeCode : o1 === o2
  }

  query(params: IRiskControlSchemeQuery): Observable<IGenericPagination<RiskControlScheme>> {
    params.insCode = this.insCode
    if (!this.isPostpositive) {
      return this.riskControlService.getList(params)
    }

    return this.riskControlService.getPostRCList(params)
  }

  getParams(): IRiskControlSchemeQuery {
    return this._params
  }

  loadMore(): void {
    if (this.isLoading) {
      return
    }
    this.isLoading = true
    this._params.page++
    this.searchChange$.next(this.getParams())
  }

  onSearch(value: string): void {
    this.isLoading = true
    this._options = []
    this._params.page = 1
    this._params.keyword = value
    this.searchChange$.next(this.getParams())
  }
}
